<?php
/**
 * User: ppjun378
 * Data: 2018/10/23
 * Time: 18:30
 */
namespace App\Service;

use App\Model\InvitationCodes;
use App\Model\LoginPermissions;
use App\Model\Wxusers;

class WxusersService
{
    /**
     * 获取用户令牌
     * @param $request
     * @return bool\int
     * @author ppjun378 <ppjun378@foxmail.com>
     */
    public static function getToken($request)
    {

        $data = $request->all();
        $open_id = $request->input('open_id', '');

        if (empty($open_id)) {
            $list['code'] = 1;
            $list['msg'] = 'error:open_id不能为空';
            return $list;
        }

        $data_exist = Wxusers::where('open_id', $open_id)->first();
        if ($data_exist) {
            $data = $data_exist->toArray();
            $user_id = $data['user_id'];
        } else {
            // 获取用户unionid
            $user_id = self::get_wx_openid($open_id);

            // $user_id = 1;

            if ($user_id === 'null') {
                $list['code'] = 1;
                $list['msg'] = 'error:传入了非法的open_id';
                return $list;
            }

        }

        $fields = [
            'open_id', //小程序open_id
            'user_id', //微信open_id
            'nick_name', //昵称
            'head_image_url', //头像
            'sex', //性别
            'country', //国家
            'province', //省
            'city', //城市
            'subscribe', //是否关注公众号
            'subscribe_time', //关注时间
            'setp', //级别
            // 'token', //用户token
            //'wxuser_id', //微信编号
            //'login_type_id', //登陆权限
        ];

        foreach ($data as $k => $v) {
            if ($v == null) {$v = '';}
            if (in_array($k, $fields) && !empty($v)) {
                $map[$k] = $v;
            }
        }

        $token = md5(uniqid(md5(microtime(true)), true)); //生成字符串
        $token = sha1($token); //加密

        // $token = '14b6f0245461416e0707e99bee3bb02a6e3e1deb';
        $map['token'] = $token;
        $map['user_id'] = $user_id;

        $data_exist = Wxusers::where('user_id', $user_id)->first();

        if ($open_id && $data_exist) {
            // 修改微信用户信息
            $result = Wxusers::where('user_id', $user_id)->update($map);

            $wxuser_id = $data_exist->toArray();
            $wxuser_id = $wxuser_id['id'];
        } else {
            // 添加微信用户信息
            $result = Wxusers::create($map);

            $wxuser_id = $result->id;

        }

        if ($result) {

            $login_type_id = $request->input('login_type_id', 0);

            // 记录权限关系表
            unset($map);
            $map['wxuser_id'] = $wxuser_id;
            $map['login_type_id'] = $login_type_id;
            $result = LoginPermissions::where($map)->first();

            if (empty($result)) {

                $str_code = $request->input('str_code', '');

                // 判断是否登陆其他接口
                if (!empty($login_type_id)) {
                    unset($map);

                    if ($login_type_id == 3 && $str_code == 'boss') {
                        // 总经理boss
                        $map['wxuser_id'] = $wxuser_id;
                        $map['login_type_id'] = 4;
                        $result = LoginPermissions::create($map);

                    } else {
                        $map['str_code'] = $str_code;
                        $map['code_type'] = $login_type_id;
                        $result = InvitationCodes::where($map)->first();
                        // 判断邀请码是否正确
                        if (empty($result)) {
                            $list['code'] = 1;
                            $list['msg'] = '请输入正确的邀请码';
                            return $list;
                        }

                    }

                }

                unset($map);
                $map['wxuser_id'] = $wxuser_id;
                $map['login_type_id'] = $login_type_id;

                $result = LoginPermissions::create($map);

            }

        }

        $list['code'] = 0;
        $list['msg'] = 'success';
        $list['data'] = array('token' => $token);
        return $list;

    }

    /**
     * 通过token获取用户数据
     * @param Request $request
     * @return mixed
     * @author ppjun378 <ppjun378@foxmail.com>
     */
    public static function getWxuserId($token)
    {

        $field = ['id'];
        $data = Wxusers::select($field)
            ->where('token', $token)
            ->first();

        if (empty($data)) {
            return 0;
        }

        $data = empty($data) ? array() : $data->toArray();

        $id = $data['id'];
        return $id;
    }

    /**
     * 验证用户token
     * @param Request $request
     * @return mixed
     * @author ppjun378 <ppjun378@foxmail.com>
     */
    public static function checkWxuser($token)
    {
        if (empty($token)) {
            $list['msg'] = 'token不能为空';
        } else {
            // $data = Wxuser
        }
    }

    /**
     * 判断微信小程序用户openid
     * @param code varchar 微信用户code
     * @return openid varchar 微信小程序唯一用户openID
     * @author ppjun378 <ppjun378@foxmail.com>
     */
    public static function get_wx_openid($code)
    {

        $appid = 'wxe2777750f42b1725';
        $secret = '2db52708c5a14b2b038c72b1b64c1c40';

        // url
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secret . '&js_code=' . $code . '&grant_type=authorization_code';

        $data = self::httpGet($url);
        $data = json_decode($data);
        return empty($data->openid) ? 'null' : $data->openid;

    }

    /**
     * 接口获取
     * @param $url string 接口链接
     * @return $res 返回接口数据
     * @author ppjun378 <ppjun378@foxmail.com>
     */
    public static function httpGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

}
